#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <cgicc/Cgicc.h>
#include "CgiWrapper.h"
#include "../ConnectMsg.h"
using std::string;using std::cout;using std::endl;
using namespace cgicc;
void err_quit(const char* msg)
{
	cout << msg << endl;
	exit(EXIT_FAILURE);
}

int main(int argc, char **argv)
{
	try
	{
		Cgicc formData;

		form_iterator usr = formData.getElement("usr");
		form_iterator pwd = formData.getElement("pwd");
		form_iterator submitType = formData.getElement("submitType");

		if (!submitType->isEmpty() && submitType != (*formData).end())
		{

			char buffer[1024];
			int index = 0;
			buffer[++index] = (**usr).size();
			strncpy(&buffer[++index],(**usr).c_str(),(**usr).size());
			index += (**usr).size();
			buffer[index++] = (**pwd).size();
			strncpy(&buffer[index],(**pwd).c_str(),(**pwd).size());

			int sockfd, n;
			sockaddr_in servaddr;

			if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
				err_quit("socket error");

			memset(&servaddr, 0, sizeof(servaddr));
			servaddr.sin_family = AF_INET;
			servaddr.sin_port = htons(19877);
			if (inet_pton(AF_INET, "127.0.0.1",&servaddr.sin_addr) <= 0)
				err_quit("inet_pton rror for ip address");

			if (connect(sockfd, (sockaddr *) &servaddr, sizeof(servaddr)) < 0)
				err_quit("connect failed");

			if (0 == (**submitType).compare("login"))
			{
				// chenck login
				msgType = LOGIN;
				buffer[0] = LOGIN;
			}
			else if(0 == (**submitType).compare("register"))
			{
				// check register
				msgType = REGISTER;
				buffer[0] = REGISTER;
			}

			index = 3+(**usr).size()+(**pwd).size();
			int nSize = 0;
			do 
			{
				nSize += write(sockfd,buffer+nSize, index-nSize);
			}
			while (nSize < index);
			if (read(sockfd,buffer,1)<0)
				err_quit("read error");
			close(sockfd);

			CGIWrapper cgi;
			cgi.HTMLHeader();
			cgi.BeginHtml();
			cgi.BeginHead("Login system");
			if ((QueryResult)buffer[0] != SUCCESS)
			{
				char arg[1024];
				snprintf(arg, 1024,"0;url=/cgi-bin/errorPage?submitType=%d&errCode=%d",
						msgType, buffer[0]);
				cgi.Meta("refresh", arg);	
			}
			else
			{
				char arg[1024];
				snprintf(arg, 1024, "0;url=/cgi-bin/login?submitType=%d&usr=%s",
						msgType, (**usr).c_str());
				cgi.Meta("refresh", arg);
			}
			cgi.EndHead();
			cgi.BeginBody();
			cgi.EndBody();
			cgi.EndHtml();
		}
	}
	catch(...)
	{
		// handle any errors here.
		cout << "ERROR!!" << endl;
	}
	return 0;   // To avoid Apache errors.
}
